/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.dwh.pretups.log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author Jose Carlos Palma
 * @version v1.0
 */
public class Logger {

    private File file;
    private PrintWriter log;
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    private boolean writable = true;
    public static Logger main;

    /**
     * Crea una instance de Logger
     * @param fileName
     * @param tipo
     */
    private Logger(String fileName) {
        this.file = new File(fileName.trim());
        try {
            this.log = new PrintWriter(new FileOutputStream(this.file, true), true);
        } catch (FileNotFoundException ex) {
            System.out.println("ERROR: no se pudo crear el archivo " + fileName + ", " + ex.getMessage());
            System.exit(1);
        }
    }

    public static void createMainInstance(String fileName) {
        Logger.main = createInstance(fileName);
    }

    /**
     * 
     * @param fileName
     * @param tipo
     * @return
     */
    public static Logger createInstance(String fileName) {
        Logger retVal = new Logger(fileName);
        return retVal;
    }

    /**
     * Retorna la fecha y hora en el formato yyyyMMddHHmmss.
     * @return
     */
    public static String getDateTime() {
        return Logger.sdf.format(new Date());
    }

    /**
     * 
     * @param line
     * @param tipo
     */
    public void println(String line, String tipo) {
        System.out.println(tipo + ">>> " + line);
        if (isWritable()) {
            log.println(tipo + "[" + getDateTime() + "]>>> " + line);
        }
    }

    /**
     * 
     * @param line
     */
    public void println(String line) {
        println(line, "INFO");
    }

    /**
     *
     * @param line
     */
    public void infoln(String line) {
        println(line, "INFO");
    }

    /**
     *
     * @param line
     */
    public void errln(String line) {
        println(line, "ERROR");
    }

    /**
     *
     * @param line
     */
    public void waringln(String line) {
        println(line, "WARNING");
    }

    /**
     * @return the writable
     */
    public boolean isWritable() {
        return this.writable;
    }

    /**
     * @param writable the writable to set
     */
    public void setWritable(boolean writable) {
        this.writable = writable;
    }
}
